package com.xucia.jsponic.servlet;

import java.util.Map;

import com.xucia.jsponic.data.GlobalData;
import com.xucia.jsponic.data.PersistableImpl;
import com.xucia.jsponic.remote.ClientConnection;
import com.xucia.jsponic.remote.JsponicAction;
import com.xucia.jsponic.remote.JsponicRequest;
import com.xucia.jsponic.security.User;

public class CreateLogin extends JsponicAction {

	@Override
	protected Object execute(Map<String, Object> parameters,
			JsponicRequest request) throws Exception {
		String username = (String) parameters.get("username");
		String password = (String) parameters.get("password");
		String emailAddress = (String) parameters.get("emailAddress");
        if (username.length() < 5) 
        	throw new RuntimeException("Your user name must be at least 5 characters long");
        if (password == null || password.length() < 6) 
        	throw new RuntimeException("Your password must be at least 6 characters long");
        if (!emailAddress.matches("[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}"))
        	throw new RuntimeException("That does not appear to be a valid email address");		
        User user = new User(username,password);
        //user.setUsername(username);
        User.authenticate(username, password);
        user.registerThisThread();
        PersistableImpl userData = user.getUserData();
        ClientConnection.getCurrentObjectResponse().setLogin(User.currentUser());
        userData.set("email",emailAddress);
        userData.set("name",username);
        ((PersistableImpl)userData.get(GlobalData.ACCESS_FIELD)).set("name",username + "'s personal access");
        return true;
    }

}
